package com.meme.editor;

import org.apache.log4j.Logger;

import com.meme.editor.event.EntityChangedEvent;


public class EntityRefLink
{
	static Logger logger = Logger.getLogger (EntityRefLink.class);
	
	EntityObject mEntityRefer;
	EntityObject mRefedEntity;
	
	public EntityRefLink (EntityObject refer)
	{
		this (refer, null);
	}
	
	public EntityRefLink (EntityObject refer, EntityObject refed)
	{
		logger.assertLog(refer != null, "refer can't be null.");
		
		mEntityRefer = refer;
		mEntityRefer.mRefedEntities.add (this);
		
		setRefedEntity (null);
	}
	
	public void destroy ()
	{
		setRefedEntity (null);
		
		mEntityRefer = null;
		mEntityRefer.mRefedEntities.remove (this);
	}
	
	public boolean isNull ()
	{
		return mRefedEntity == null;
	}
	
	public void setRefedEntity (EntityObject refed)
	{
		if( mRefedEntity == refed )
			return;
		
		if ( ! mEntityRefer.checkReferability (this, refed) )
			return;
		
		EntityObject oldrefed = mRefedEntity;
			
		// break old
		if ( mRefedEntity != null )
		{
			mRefedEntity.mEntityRefers.remove (this);			
			mRefedEntity = null;
			
			
			mEntityRefer.notifyModified (EntityChangedEvent.ModType_General);
		}
		
		
		// build new		
		if ( refed != null )
		{
			mRefedEntity = refed;
			mRefedEntity.mEntityRefers.add (this);
			
			mEntityRefer.notifyModified (EntityChangedEvent.ModType_General);
		}
		
		//
		if ( oldrefed != mRefedEntity )
			mEntityRefer.notifyEntityRefLinkModified (this);
	}
	

	
	public EntityObject getEntityRefer ()
	{
		return mEntityRefer;
	}
	
	public EntityObject getRefedEntity ()
	{
		return mRefedEntity;
	}
}
